//
//  My_ViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/22.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "My_ViewController.h"
#import "Follow_ViewController.h"
#import "Fans_ViewController.h"
#import "MMDrawerController.h"
#import "RecordViewController.h"

#import "MessageViewController.h"
#import "system_MessageViewController.h"

#import "worksHeader.h"
#import "jiFenModel.h"
#import "IsLogout.h"

#import "UIViewExt.h"
#import "UIImage+thumbImage.h"
#import "UIViewController+MMDrawerController.h"

#import "AppDelegate.h"
#import "MJRefresh.h"
#import "MozTopAlertView.h"
#import "MobClick.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "JCAlertView.h"
#import "EMSDK.h"
#import "WZLBadgeImport.h"
@interface My_ViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UITextFieldDelegate, MJRefreshBaseViewDelegate,EMChatManagerDelegate>
{
    int page;
    int pages;
    NSInteger allMessageCount;
    NSString *_filePath;

    
    MJRefreshSystemHeaderView *refreshHeader;
    MJRefreshFooterView *refreshFooter;
    UIImageView *_timeLine;
    NSString *playingAudioId;
    NSNumber *uploaded;
    NSNumber *isUploading;
    JCAlertView *_alert;
    JCAlertView *_jifenAlert;
}

@property (strong, nonatomic) UIScrollView *ownScrollView;
@property (strong, nonatomic) ownInforView *HeaderInfor;
@property (strong, nonatomic) UITableView *worksTableView;
@property (strong, nonatomic) UIImageView *NoworksView;
@property (strong, nonatomic) NSMutableArray *worksArray;
@property (strong, nonatomic) playerTableViewController *player;
@property (strong, nonatomic) UIButton *btn;
@property (strong, nonatomic) worksHeader *header;
@end

@implementation My_ViewController
-(instancetype)initWithSelfUid:(NSString *)uid
{
    self = [super init];
    if (self) {
        self.selfUid = uid;
        self.worksArray = [[NSMutableArray alloc] init];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"my_work"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadSelfData:content pag:1];
            page = 1;
        } else {
//            [header beginRefreshing];
            [self AFNetworking:1 uid:uid refreshing:nil];
        }

        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont boldSystemFontOfSize:20];
        self.navigationItem.titleView = _titleLabel;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadState:) name:@"uploadState" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteWork:) name:@"delete" object:nil];
        uploaded = [NSNumber numberWithBool:NO];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeProgress:) name:@"UploadPercent" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUnreadSystemMessageCount:) name:@"checkUnreadMessageCount" object:nil];
        [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];

    }
    return self;
}
- (void)getUnreadSystemMessageCount:(NSNotification *)notification
{
    NSString *unreadCountStr = notification.object;
    self.sysMessageCount = unreadCountStr.integerValue;
    [self checkUnreadMessage];
}
- (void)uploadState:(NSNotification *)notification
{
    NSString *num = notification.object;
    if ([num isEqualToString:@"upload"]) {
        isUploading = [NSNumber numberWithBool:YES];
//        [MozTopAlertView showWithType:MozAlertTypeInfo text:@"正在上传" parentView:self.view];
        _header.ProgressView.hidden = NO;
        [_header uploadState];
//        self.tabBarController.tabBar.userInteractionEnabled = NO;
    } else if ([num isEqualToString:@"success"]) {
        uploaded = [NSNumber numberWithBool:YES];
        [refreshHeader beginRefreshing];
        isUploading = [NSNumber numberWithBool:NO];
//        self.tabBarController.tabBar.userInteractionEnabled = YES;
    } else if ([num isEqualToString:@"false"]) {
        [MozTopAlertView showWithType:MozAlertTypeError text:@"上传失败" parentView:self.view];
        NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[_header searchDraftWork] error:nil];
        if (fileList.count > 1) {
            [_header layoutSubviews];
        } else {
            _worksTableView.tableHeaderView = nil;
        }
    }
}
- (void)changeProgress:(NSNotification *)notification
{
    NSNumber *progress = notification.object;
    [_header.ProgressView setProgress:progress.floatValue animated:YES];
}
- (void)deleteWork:(NSNotification *)notification
{
    [refreshHeader beginRefreshing];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] == nil) {
        //我的
        //提示请先登陆
        self.titleLabel.text = nil;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        view.backgroundColor = [UIColor colorWithWhite:0.971 alpha:1.000];
        view.tag = 1205;
        [self.view addSubview:view];
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{
            MMDrawerController *controller = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
            UITabBarController *tab = (UITabBarController *)controller.centerViewController;
            tab.selectedIndex = 0;
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];
    } else {
        if (_HeaderInfor) {
            [_HeaderInfor requestOwnInfor:_selfUid];
        }
        [MobClick beginLogPageView:@"我的"];
        [self checkUnreadMessage];
    }
    if (_worksTableView && isUploading.boolValue == NO) {
        if (_worksTableView.tableHeaderView == nil) {
            NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[_header searchDraftWork] error:nil];
            if (fileList.count > 1) {
                _worksTableView.tableHeaderView = _header;
                [_header layoutSubviews];
            }
        } else {
            NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[_header searchDraftWork] error:nil];
            if (fileList.count > 1) {
                [_header layoutSubviews];
            } else {
                _worksTableView.tableHeaderView = nil;
            }
        }
    }
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [MobClick endLogPageView:@"我的"];
//    [[EMClient sharedClient].chatManager removeDelegate:self];
}
- (void)viewDidLoad{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 27, 27);
    [rightBtn setImage:[UIImage imageNamed:@"setting_btn"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(clickSettingBtn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *setting = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = setting;
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 30, 30);
    [leftBtn setImage:[UIImage imageNamed:@"message"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(clickMessageBtn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *message = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = message;
    
    self.ownScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 45)];
    _ownScrollView.delegate = self;
    _ownScrollView.contentSize = CGSizeMake(0, 0);
    [self.view addSubview:_ownScrollView];
    [self createOwnInforView];
    
    [self createWorksTableview];
}
- (void)createOwnInforView
{
    self.HeaderInfor = [[ownInforView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height *0.2382) ownuid:_selfUid viewController:self];
//    _HeaderInfor.backgroundColor =[UIColor redColor];
    _HeaderInfor.backgroundColor = [UIColor clearColor];
    [_ownScrollView addSubview:_HeaderInfor];
    _HeaderInfor.userInteractionEnabled = YES;
    _HeaderInfor.avatar.userInteractionEnabled = YES;
    [_HeaderInfor.headerButton addTarget:self action:@selector(editMessageClick) forControlEvents:UIControlEventTouchUpInside];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(BigAvatr)];
    [_HeaderInfor.avatar addGestureRecognizer:tapGesture];
    [_HeaderInfor.followedBtn addTarget:self action:@selector(goToFollowVC) forControlEvents:UIControlEventTouchUpInside];
    [_HeaderInfor.fansBtn addTarget:self action:@selector(goToFansVC) forControlEvents:UIControlEventTouchUpInside];

}
- (void)createWorksTableview
{
    page = 1;
    self.worksTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _HeaderInfor.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - _HeaderInfor.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    _worksTableView.showsVerticalScrollIndicator = NO;
    _worksTableView.delegate = self;
    _worksTableView.dataSource = self;
    _worksTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    


    self.header = [[worksHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.21 * self.view.frame.size.height)];
    _header.backgroundColor = [UIColor whiteColor];
    [_header.continueBtn addTarget:self action:@selector(driftContinue:) forControlEvents:UIControlEventTouchUpInside];
    [_header.deleteBtn addTarget:self action:@selector(driftDelete:) forControlEvents:UIControlEventTouchUpInside];
    _worksTableView.tableHeaderView = _header;
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[_header searchDraftWork] error:nil];
    if (fileList.count <= 1) {
        _worksTableView.tableHeaderView = nil;
    }
    [_ownScrollView addSubview:_worksTableView];
    [_ownScrollView bringSubviewToFront:_HeaderInfor];
    
    refreshHeader = [MJRefreshSystemHeaderView header];
    refreshHeader.scrollView = _worksTableView;
    refreshHeader.delegate = self;
    refreshFooter = [MJRefreshFooterView footer];
    refreshFooter.scrollView = _worksTableView;
    refreshFooter.delegate = self;
    if (pages == 1) {
        refreshFooter.hidden = YES;
    }

    
    _timeLine = [[UIImageView alloc]initWithFrame:CGRectMake(16, -_HeaderInfor.frame.size.height * 1.5, 1.5,_HeaderInfor.frame.size.height * 1.5)];
    _timeLine.backgroundColor = [UIColor blackColor];
    [_worksTableView.viewForBaselineLayout addSubview:_timeLine];
    _timeLine.alpha = 1;
}
#pragma mark -
#pragma mark 环信
- (void)didReceiveMessages:(NSArray *)aMessages
{
    BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
    if (!isAppActivity && aMessages.count > 0) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //本地推送
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            NSString *str = @"http://123.57.1.143/api/message/selfpush";
            
            NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
            [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
            [manager GET: str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        });
    }
        [self checkUnreadMessage];
}
- (void)checkUnreadMessage
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger BadgeCount = 0;
    for (EMConversation *converstion in conversations) {
        BadgeCount += converstion.unreadMessagesCount;
    }
    allMessageCount = self.sysMessageCount + BadgeCount;
        MMDrawerController *drawer = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
        
            UITabBarController *tab = (UITabBarController *)drawer.centerViewController;
        UITabBarItem *lastItem = tab.tabBar.items.lastObject;
        //it is necessary to adjust badge position
        lastItem.badgeCenterOffset = CGPointMake(-25, 8);
    self.navigationItem.leftBarButtonItem.badgeCenterOffset = CGPointMake(-5, 8);
    if (allMessageCount > 0) {
        [lastItem showBadge];
        [self.navigationItem.leftBarButtonItem showBadgeWithStyle:WBadgeStyleNumber value:allMessageCount animationType:WBadgeAnimTypeNone];
    } else {
        [lastItem clearBadge];
        [self.navigationItem.leftBarButtonItem clearBadge];
    }
     [[UIApplication sharedApplication] setApplicationIconBadgeNumber:allMessageCount];
}
#pragma mark -
#pragma mark tableview 协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _worksArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (0.24 * self.view.frame.size.height);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *worksTableIdentifer = @"works";
    WorksTableViewCell *workstabelCell = [tableView dequeueReusableCellWithIdentifier:worksTableIdentifer];
    if (workstabelCell == nil) {
        workstabelCell = [[WorksTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:worksTableIdentifer];
    }
    if (_worksArray.count > 0) {
        workInfor *model = _worksArray[indexPath.row];
        workstabelCell.listdataModel = model;
    }
    
    return workstabelCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UINavigationController *nv = (UINavigationController *)self.mm_drawerController.rightDrawerViewController;
    self.player = (playerTableViewController *)nv.topViewController;
    WorksTableViewCell *cell = (WorksTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.listdataModel.play_count = [NSString stringWithFormat:@"%d",cell.listdataModel.play_count.intValue + 1];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isPlay = [userDefaults objectForKey:@"isWiFiPlay"];
    NSString *pppp=[NSString stringWithFormat:@"%u",[self getNetworkTypeFromStatusBar]];
    
    if (([isPlay isEqualToString:@"1"]&&[pppp isEqualToString:@"5"])||[pppp isEqualToString:@"5"]||([isPlay isEqualToString:@"0"]&&![pppp isEqualToString:@"0"])||isPlay==nil){
        Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
        workInfor *model = _worksArray[indexPath.row];
        
        NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", model.id];
          AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
        [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSDictionary *dataDic = [dic valueForKey:@"data"];
            NSDictionary *linksDic = [dic valueForKey:@"links"];
            [playModel setValuesForKeysWithDictionary:dataDic];
            if ([[dic allKeys] containsObject:@"meta"]) {
                NSDictionary *meta = [dic valueForKey:@"meta"];
                NSString *userAvatar = [meta valueForKey:@"userAvatar"];
                _player.locUserAvatar = userAvatar;
//                NSArray *array = [meta valueForKey:@"playlist"];
//                _player.playList = [NSMutableArray arrayWithArray:array]
                ;
                playModel.comment_count = [meta valueForKey:@"count"];
                ;
            }
            _player.waveform = [linksDic valueForKey:@"waveform"];
            _player.workID = model.id;
            _player.isSelf = YES;
            //保存是否love
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *islove = @"0";
            if ([[dataDic objectForKey:@"liked"]boolValue]==YES) {
                islove = @"1";
            }else{
                islove = @"0";
            }
            [userDefaults setObject:islove forKey:@"isLove"];
            [userDefaults synchronize];
            [_player reloadViews:playModel];
            [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
            }];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }else{
        //提示已开启仅Wi-Fi下播放功能
        [JCAlertView showOneButtonWithTitle:@"你已开启仅Wifi环境播放" Message:@"可以去设置关闭此功能" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你已开启仅Wifi环境播放" message:@"可以去设置关闭此功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        // optional - add more buttons:
//        alert.tag = 80000;
//        [alert show];
    }
}
#pragma mark -
#pragma makr 网络请求
-(NETWORK)getNetworkTypeFromStatusBar {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])     {
            dataNetworkItemView = subview;
            break;
        }
    }
    NETWORK nettype = NETWORK_NONE;
    NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    nettype = [num intValue];
    return nettype;
}
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshSystemHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        refreshFooter.hidden = NO;
        [_worksArray removeAllObjects];
        [self AFNetworking:page uid:_selfUid refreshing:refreshView];
        [_HeaderInfor requestOwnInfor:_selfUid];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            refreshFooter.hidden = YES;
        } else {
            page++;
            [self AFNetworking:page uid:_selfUid refreshing:refreshView];
        }
    }
}

- (void)AFNetworking:(int)pag uid:(NSString *)uid refreshing:(MJRefreshBaseView *)refreshView
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/feeds?p=%d", uid, pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];

      AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (pag == 1) {
            //            BOOL result = [operation.responseData writeToFile:<#(nonnull NSString *)#> atomically:<#(BOOL)#>]
        }
        [self reloadSelfData:responseObject pag:pag];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refreshView endRefreshing];
            NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[_header searchDraftWork] error:nil];
            if (fileList.count > 1) {
                [_header layoutSubviews];
            } else {
                _worksTableView.tableHeaderView = nil;
            }
        });
        if (![[[NSUserDefaults standardUserDefaults] valueForKey:@"alert"] isEqualToString:@"yes"]  && uploaded.boolValue == YES && [AppDelegate shareDelegate].weixinShare.boolValue == YES) {
            UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 90, 230)];
            customView.backgroundColor = [UIColor whiteColor];
            
            UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [doneBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
            doneBtn.backgroundColor = [UIColor whiteColor];
            doneBtn.frame = CGRectMake(0,0, 25, 25);
            doneBtn.center = CGPointMake(20, 20);
            [customView addSubview:doneBtn];
            [doneBtn addTarget:self action:@selector(cancelAlert) forControlEvents:UIControlEventTouchUpInside];
            
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, customView.frame.size.width, customView.frame.size.height / 6)];
            titleLabel.text = @"上传成功";
            titleLabel.font = [UIFont boldSystemFontOfSize:21];
            titleLabel.textColor = [UIColor blackColor];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            [customView addSubview:titleLabel];
            
            UILabel *deLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, titleLabel.frame.origin.y + titleLabel.frame.size.height, 210, titleLabel.frame.size.height * 2)];
            deLabel.center = CGPointMake(customView.center.x, deLabel.frame.origin.y + titleLabel.frame.size.height + 10);
            deLabel.text = @"分享新作品到朋友圈并收集25个赞，即会被首页置顶，并赚取双倍作品积分";
            deLabel.textAlignment = NSTextAlignmentCenter;
            deLabel.lineBreakMode = NSLineBreakByWordWrapping;
            deLabel.numberOfLines = 0;
            [customView addSubview:deLabel];
            
            UIButton *cancelbtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [cancelbtn setTitle:@"立即分享" forState:UIControlStateNormal];
            cancelbtn.backgroundColor = [UIColor blackColor];
            cancelbtn.frame = CGRectMake(10, customView.frame.size.height - (customView.frame.size.height / 5 - 10) - 10, customView.frame.size.width - 20, customView.frame.size.height / 5 - 10);
            [customView addSubview:cancelbtn];
            [cancelbtn addTarget:self action:@selector(shareWork) forControlEvents:UIControlEventTouchUpInside];
            
            _alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
            [_alert show];
            uploaded = [NSNumber numberWithBool:NO];
        }
        
        if ([AppDelegate shareDelegate].weixinShare.boolValue == YES && [WXApi isWXAppInstalled] && [[[NSUserDefaults standardUserDefaults] valueForKey:@"alert"] isEqualToString:@"yes"]) {
            //            分享朋友圈
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self shareToWeChat];
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)reloadSelfData:(id)responseObject pag:(int)pag
{
    NSDictionary *data = [responseObject valueForKey:@"data"];
    for (NSDictionary *dic in data) {
        workInfor *model = [[workInfor alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [_worksArray addObject:model];
    }
    
    NSDictionary *meta = [responseObject valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            refreshFooter.hidden = YES;
        }
    }
    if (_worksArray.count > 0) {
        if ([_worksTableView isHidden]) {
            _worksTableView.hidden = NO;
            _NoworksView.hidden = YES;
        }
    } else {
        _NoworksView.hidden = NO;
        _worksTableView.hidden = YES;
    }
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[_header searchDraftWork] error:nil];
    if (fileList.count == 0 ) {
        _worksTableView.tableHeaderView = nil;
    }
    [_worksTableView reloadData];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int header_height = (int)ceilf(_HeaderInfor.frame.size.height);
    int ownOffset = (int)_ownScrollView.contentOffset.y;
    if (![refreshHeader isRefreshing]) {
        if (_worksTableView.contentOffset.y > 10 && ownOffset !=(int)header_height) {
            if ([UIScreen mainScreen].bounds.size.width == 414.00) {
                _worksTableView.frame = CGRectMake(0, 175, self.view.frame.size.width, self.view.frame.size.height- 49 );
            } else {
            _worksTableView.frame = CGRectMake(0, _HeaderInfor.frame.size.height, self.view.frame.size.width, self.view.frame.size.height- 49 );
            }
            [UIView animateWithDuration:0.2 animations:^{
                _ownScrollView.contentOffset = CGPointMake(0, _HeaderInfor.frame.size.height);
            }];
            
        }
        
        if (scrollView.contentOffset.y < -10 && _ownScrollView.contentOffset.y != 0) {
            _worksTableView.frame = CGRectMake(0, _HeaderInfor.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - 64 - 49);
            [UIView animateWithDuration:0.2 animations:^{
                _ownScrollView.contentOffset = CGPointMake(0, 0);
            }];
        }
    } 
}
#pragma mark -
#pragma mark 按钮点击
- (void)clickMessageBtn:(UIButton *)sender
{
    MessageViewController *ceon = [[MessageViewController alloc] initWithSystemMessageCount:_sysMessageCount];
    [self.navigationController pushViewController:ceon animated:YES];
}
- (void)clickSettingBtn:(UIButton *)sender
{
    set_ViewController *setVC=[[set_ViewController alloc]init];
    setVC.account = self.account;
    [self.navigationController pushViewController:setVC animated:YES];
}
- (void)editMessageClick
{
    jiFenModel *jifen = [[jiFenModel alloc] init];
    [jifen showJiFen:self];
}

- (void)goToFollowVC
{
    Follow_ViewController *follow = [[Follow_ViewController alloc] initWithSelfUid:_selfUid];
    [self.navigationController pushViewController:follow animated:YES];
}
- (void)goToFansVC
{
    Fans_ViewController *fans = [[Fans_ViewController alloc] initWithSelfUid:_selfUid];
    [self.navigationController pushViewController:fans animated:YES];
}

- (void)driftContinue:(UIButton *)sender
{
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *DouNiu = [strUrl stringByAppendingPathComponent:@"DouNiu"];
    NSArray *fileList = [[NSArray alloc] init];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:DouNiu error:&error];
    NSString *workName = [fileList lastObject];
    RecordViewController *rec = [[RecordViewController alloc] init];
    rec.isDraft = [NSNumber numberWithBool:YES];
    rec.draftAudioPath = workName;
    NSString *waveformPt = [[DouNiu stringByAppendingPathComponent:workName] stringByAppendingPathComponent:@"waveformComplete"];
    rec.waveform = [NSArray arrayWithContentsOfFile:waveformPt];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rec];
    [self presentViewController:nav animated:YES completion:^{
        
    }];
}
- (void)driftDelete:(UIButton *)sender
{
    [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"是否删除草稿" ButtonType: JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:^{
        
    } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
        NSError *error = nil;
        NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *DouNiu = [strUrl stringByAppendingPathComponent:@"DouNiu"];
        NSArray *fileList = [[NSArray alloc] init];
        //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
        fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:DouNiu error:&error];
        NSString *filename = [fileList lastObject];
        NSString *workPath = [DouNiu stringByAppendingPathComponent: filename];
        [[NSFileManager defaultManager] removeItemAtPath:workPath error:&error];
        fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:DouNiu error:&error];
        if (fileList.count >= 1) {
            [_header layoutSubviews];
        } else {
            _worksTableView.tableHeaderView = nil;
        }
        [AppDelegate shareDelegate].weixinShare = [NSNumber numberWithBool:NO];
    }];
}
#pragma mark - 
#pragma mark 头像缩放
- (void)BigAvatr
{
    UIView *_blackview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    _blackview.backgroundColor = [UIColor whiteColor];
    _blackview.alpha = 0;
    _blackview.tag = 203;
    _blackview.userInteractionEnabled = YES;
    [self.view addSubview:_blackview];
    UIImageView *bigImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, _blackview.frame.size.height / 2 - (_blackview.frame.size.width / 2), _blackview.frame.size.width, _blackview.frame.size.width)];
    [_blackview addSubview:bigImage];
    [UIView animateWithDuration:0.25f animations:^{
        _blackview.alpha = 1;
        if ([_HeaderInfor.userInformation.avatar isKindOfClass:[NSNull class]] || _HeaderInfor.userInformation.avatar.length < 5) {
            [bigImage setImage:[UIImage imageNamed:@"default_head@3x"]];
        } else {
            [bigImage setImageWithURL:[NSURL URLWithString:_HeaderInfor.userInformation.avatar]];
        }
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(smallAvatar)];
    [_blackview addGestureRecognizer:tap];
}
- (void)smallAvatar
{
    UIView *blackView = [self.view viewWithTag:203];
    [UIView animateWithDuration:0.5f animations:^{
        blackView.alpha = 0.0f;
    }completion:^(BOOL finished) {
        [blackView removeFromSuperview];
    }];
}
- (void)cancelAlert
{
    [_alert dismissWithCompletion:^{
        
    }];
}
- (void)shareWork
{
    [_alert dismissWithCompletion:^{
    }];
    if ([AppDelegate shareDelegate].weixinShare.boolValue == YES && [WXApi isWXAppInstalled]) {
        [self shareToWeChat];
    }
}
#pragma mark -
#pragma mark 修改 title
- (void)changeTitle:(NSNotification *)notification
{
    NSDictionary *dic = notification.object;
    self.titleLabel.text = [dic valueForKey:@"username"];
}
- (void)shareToWeChat
{
    workInfor *model = [_worksArray firstObject];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:model.cover]];
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = [NSString stringWithFormat:@"%@｜声音实验室",model.title];
    message.description = [NSString stringWithFormat:@"来声音实验室听 %@ 的更多作品",self.title];

    UIImage *thumbImage = [UIImage generatePhotoThumbnail:[UIImage imageWithData:data]];
    
    [message setThumbImage:thumbImage];
    WXMusicObject *ext = [WXMusicObject object];
    ext.musicUrl = [NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", model.id];//@"";
    ext.musicDataUrl = [[NSUserDefaults standardUserDefaults] valueForKey:@"tmpfile"];
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    //    req.text = @"aaaaaaaaa"
    req.bText = NO;
    req.message = message;
    req.scene = 1;
    
//    BOOL result =
    [WXApi sendReq:req];
    [AppDelegate shareDelegate].weixinShare = [NSNumber numberWithBool:NO];
}
- (void)showJifenAlert:(id)responseObject
{
    UIImageView *qiandaoView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 70, 360)];
    qiandaoView.backgroundColor = [UIColor whiteColor];
    qiandaoView.image = [UIImage imageNamed:@"bigPlaceholderimage"];
    qiandaoView.contentMode = UIViewContentModeScaleAspectFill;
    qiandaoView.layer.masksToBounds = YES;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage
                      imageNamed:@"close"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(closeJifenAlert:) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(10, 10, 30, 30);
    [qiandaoView addSubview:button];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, button.frame.size.height, qiandaoView.frame.size.width, 40)];
    title.text = @"积分数据";
    title.font = [UIFont boldSystemFontOfSize:25];
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = [UIColor blackColor];
    [qiandaoView addSubview:title];
    
    UILabel *detile = [[UILabel alloc] initWithFrame:CGRectMake(50, title.bottom + 5, 250, 30)];
    detile.textColor = [UIColor blackColor];
    //    detile.textAlignment = NSTextAlignmentCenter;
    detile.text = [NSString stringWithFormat:@"被        赞：%@P × %@",[responseObject valueForKey:@"digscore"],[responseObject valueForKey:@"dig"]];
    detile.textColor = [UIColor colorWithHue:0 saturation:0 brightness:0.59 alpha:1];
    detile.center = CGPointMake(qiandaoView.center.x + 30, detile.center.y);
    [qiandaoView addSubview:detile];
    
    UILabel *beizan = [[UILabel alloc] initWithFrame:CGRectMake(50, detile.bottom - 3, 250, 30)];
    //    beizan.backgroundColor = [UIColor redColor];
    if ([[responseObject valueForKey:@"login"] integerValue] != 0) {
        beizan.text =
        [NSString stringWithFormat:@"签        到：%@P      complete",[responseObject valueForKey:@"loginscore"]];
    } else {
        beizan.text =
        [NSString stringWithFormat:@"签        到：%@P",[responseObject valueForKey:@"loginscore"]];
    }
    beizan.textColor = [UIColor colorWithHue:0 saturation:0 brightness:0.59 alpha:1];
    beizan.center = CGPointMake(qiandaoView.center.x + 30, beizan.center.y);
    [qiandaoView addSubview:beizan];
    
    UILabel *xinzuopin = [[UILabel alloc] initWithFrame:CGRectMake(50, beizan.bottom - 3, beizan.width, 30)];
    if ([[responseObject valueForKey:@"work"] integerValue] != 0) {
//        xinzuopin.text = @"发  作  品：✔️ ";
        xinzuopin.text =
        [NSString stringWithFormat:@"发  作  品：%@P      complete",[responseObject valueForKey:@"workscore"]];
    } else {
//        xinzuopin.text = @"发  作  品：✖️ ";
        xinzuopin.text =
        [NSString stringWithFormat:@"发  作  品：%@P",[responseObject valueForKey:@"workscore"]];
    }
//    xinzuopin.text = [NSString stringWithFormat:@"发  作  品：%@P × %@",[responseObject valueForKey:@"workscore"],[responseObject valueForKey:@"work"]];
    xinzuopin.textColor = [UIColor colorWithHue:0 saturation:0 brightness:0.59 alpha:1];
    xinzuopin.center = CGPointMake(qiandaoView.center.x + 30, xinzuopin.center.y);
    [qiandaoView addSubview:xinzuopin];
    
    UILabel *tuijian = [[UILabel alloc] initWithFrame:CGRectMake(50, xinzuopin.bottom - 3, xinzuopin.width, 30)];
    if ([[responseObject valueForKey:@"topic"] integerValue] != 0) {
        tuijian.text =
        [NSString stringWithFormat:@"参与话题：%@P      complete",[responseObject valueForKey:@"topicscore"]];
    } else {
        tuijian.text =
        [NSString stringWithFormat:@"参与话题：%@P",[responseObject valueForKey:@"topicscore"]];
    }
    tuijian.textColor = [UIColor colorWithHue:0 saturation:0 brightness:0.59 alpha:1];
    tuijian.center = CGPointMake(qiandaoView.center.x + 30, tuijian.center.y);
    [qiandaoView addSubview:tuijian];
    
    UILabel *huati = [[UILabel alloc] initWithFrame:CGRectMake(50, tuijian.bottom - 3, tuijian.width, 30)];
    if ([[responseObject valueForKey:@"push"] integerValue] != 0) {
        huati.text =
        [NSString stringWithFormat:@"特殊贡献：%@P      complete",[responseObject valueForKey:@"pushscore"]];
    } else {
        huati.text =
        [NSString stringWithFormat:@"特殊贡献：%@P",[responseObject valueForKey:@"pushscore"]];
    }
    huati.textColor = [UIColor colorWithHue:0 saturation:0 brightness:0.59 alpha:1];
    huati.center = CGPointMake(qiandaoView.center.x + 30, huati.center.y);
    [qiandaoView addSubview:huati];
    
    UILabel *jifen = [[UILabel alloc] initWithFrame:CGRectMake(50, huati.bottom + 8, qiandaoView.frame.size.width - 100, 60)];
    jifen.text = [NSString stringWithFormat:@"%@",[responseObject valueForKey:@"score"]];
    //    jifen.font = [UIFont systemFontOfSize:55];
    jifen.font = [UIFont fontWithName:@"DBLCDTempBlack" size:55];
    jifen.textAlignment = NSTextAlignmentCenter;
    [qiandaoView addSubview:jifen];
    
    UIButton *done = [UIButton buttonWithType:UIButtonTypeCustom];
    if ([[responseObject valueForKey:@"sign"] isEqualToString:@"errors"]) {
        [done setTitle:@"已签到" forState: UIControlStateNormal];
        done.backgroundColor = [UIColor colorWithRed:0.478 green:0.490 blue:0.506 alpha:1.00];//[UIColor blackColor];
    } else {
        [done setTitle:@"签到" forState: UIControlStateNormal];
        done.backgroundColor = [UIColor blackColor];
        [done addTarget:self action:@selector(sign:) forControlEvents:UIControlEventTouchUpInside];
    }
    done.frame = CGRectMake(40, jifen.bottom, qiandaoView.frame.size.width - 80, 50);
    //    done.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [done setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [qiandaoView addSubview:done];
    qiandaoView.userInteractionEnabled = YES;
    _jifenAlert = [[JCAlertView alloc] initWithCustomView:qiandaoView dismissWhenTouchedBackground:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_jifenAlert show];
    });
}
- (void)closeJifenAlert:(id)sender
{
    [_jifenAlert dismissWithCompletion:nil];
}
- (void)sign:(UIButton *)sender
{
    PlazzViewController *PLAZ = (PlazzViewController *)[[self.tabBarController.viewControllers firstObject] topViewController];
    [IsLogout userIsLogout:PLAZ Alert:NO];
    [self closeJifenAlert:sender];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
